package com.alex.service;

import com.alex.dao.OfflineMessage;
import com.alex.dao.OfflineMessageRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 离线消息-实现
 */
@Service(value = "offlineMessageService")
public class OfflineMessageServiceImpl implements OfflineMessageService {

    @Resource
    private OfflineMessageRepository messageRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(String userId, String message) {
        OfflineMessage newMessage = new OfflineMessage();
        newMessage.setUserId(userId);
        newMessage.setMessage(message);
        newMessage.setStatus(1);

        messageRepository.save(newMessage);
    }

    @Override
    public List<OfflineMessage> listByUserIdOrderByDate(String userId) {
        return messageRepository.queryAllByUserIdAndStatus(userId, 1);
    }

    @Override
    public void updateMessageStatus(Long id) {
        Optional<OfflineMessage> message = messageRepository.findById(id);
        if (message.isPresent()) {
            OfflineMessage offlineMessage = message.get();
            offlineMessage.setStatus(2);

            messageRepository.saveAndFlush(offlineMessage);
        }
    }
}
